//
//  LeftMenuView.m
//  NOAHWM
//
//  Created by Ryan on 13-5-28.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "LeftMenuView.h"
#import "NYMemberCenterDataManager.h"
#import "MenuDataManager.h"

#define kLocalMenuFileName @"LeftMenu"

@interface LeftMenuView()

@property (nonatomic, retain) NSArray *menuArray;
@property (nonatomic, retain) NSMutableDictionary *sectionDict;
@property (nonatomic, retain) NSIndexPath *currentIndexPath;

@property (nonatomic, retain) NSArray *localMenuArray;

@end

@implementation LeftMenuView

@synthesize refreshView,bgImageView;
@synthesize menuArray;
@synthesize sectionDict,currentIndexPath;
@synthesize localMenuArray;
@synthesize editButton;
@synthesize editMode;

- (void)setEditMode:(EditMenuMode)em
{
    editMode = em;
    if(em == kEditNone)
    {
        self.editButton.alpha = 0;
        self.refreshView.refreshTableView.editing = NO;
    }
    else if(em == kEditingMenu)
    {
        self.editButton.alpha = 1.f;
        [self.editButton setImage:[UIImage imageNamed:@"btn_menu_edit_normal@2x.png"] forState:UIControlStateNormal];
        [self.editButton setImage:[UIImage imageNamed:@"btn_menu_edit_highlighted@2x.png"] forState:UIControlStateHighlighted];
        [self.refreshView.refreshTableView setEditing:NO animated:YES];
    }
    else
    {
        self.editButton.alpha = 1.f;
        [self.editButton setImage:[UIImage imageNamed:@"btn_menu_confirm_normal@2x.png"] forState:UIControlStateNormal];
        [self.editButton setImage:[UIImage imageNamed:@"btn_menu_confirm_highlighted@2x.png"] forState:UIControlStateHighlighted];
        [self.refreshView.refreshTableView setEditing:YES animated:YES];
    }
}

#pragma mark - Public methods
- (void)reloadState
{
//    self.refreshView.refreshTableView.allowsSelectionDuringEditing = YES;
    if([[NYMemberCenterDataManager sharedManager] isLogin])
    {
        self.editMode = kEditingMenu;
    }
    else
    {
        self.editMode = kEditNone;
    }
    [self.refreshView startManualLoading];
}

- (void)resetSectionsState
{
    for(MenuSectionView *msv in [self.sectionDict allValues])
    {
        [msv setSectionHighlighted:NO];
    }
}

- (void)resetCellState
{
    if(self.currentIndexPath)
    {
        [self.refreshView.refreshTableView deselectRowAtIndexPath:self.currentIndexPath animated:NO];
    }
}

#pragma mark - Notification methods

- (void)loadFirstTabWithNotification:(NSNotification *)notification
{
    MenuSectionView *msv = [self.sectionDict objectForKey:@"0"];
    [self didSelectedWithSection:msv];
}

- (void)refreshPersonalInfoResponseWithNotification:(NSNotification *)notification
{
//    [NYMemberCenterDataManager sharedManager].loginMember.is_gesture_password = @"1";
//    [NYMemberCenterDataManager sharedManager].loginMember.gesture_password = @"";
    
    //存在手势密码，打开解锁页否则设置解锁密码
    if([NYMemberCenterDataManager sharedManager].loginMember.gesture_password &&
       ![[NYMemberCenterDataManager sharedManager].loginMember.gesture_password isEqualToString:@""])
        [[NSNotificationCenter defaultCenter] postNotificationName:kShowPatternLockViewNotification object:[NSNumber numberWithInt:1]];
    else
        [[NSNotificationCenter defaultCenter] postNotificationName:kShowPatternLockViewNotification object:[NSNumber numberWithInt:0]];
}

- (void)getMenuSucceedWithNotification:(NSNotification *)notification
{
    self.sectionDict = [NSMutableDictionary dictionary];
    self.currentIndexPath = nil;
    [self.refreshView doneLoadingTableViewData];
    [self.refreshView.refreshTableView reloadData];
    //菜单加载成功之后默认显示第一个tab内容
    [self performSelector:@selector(loadFirstTabWithNotification:) withObject:nil afterDelay:0];
}

- (void)getMenuErrorWithNotification:(NSNotification *)notification
{
    self.sectionDict = [NSMutableDictionary dictionary];
    self.currentIndexPath = nil;
    [self.refreshView doneLoadingTableViewData];
}

- (void)synMenuErrorWithNotification:(NSNotification *)notification
{
    
}

- (void)userChangeWithNotification:(NSNotification *)notification
{
    [self reloadState];
}

#pragma mark - UIView methods

- (void)awakeFromNib
{
    [super awakeFromNib];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadFirstTabWithNotification:) name:kLoadLeftMenuFirstTabNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshPersonalInfoResponseWithNotification:) name:kSucceedGetPersonalInfoNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getMenuSucceedWithNotification:) name:kGetMenuSucceedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getMenuErrorWithNotification:) name:kGetMenuErrorNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(synMenuErrorWithNotification:) name:kSynMenuErrorNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userChangeWithNotification:) name:kUserChangeNotification object:nil];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:kLocalMenuFileName ofType:@"plist"];
    self.localMenuArray = [NSArray arrayWithContentsOfFile:path];
    
    self.refreshView.refreshTableView.backgroundColor = [UIColor clearColor];
    self.refreshView.refreshTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    if(Is4InchSizeScreen)
    {
        self.bgImageView.image = [UIImage imageNamed:@"bg_leftMenu@2x.png"];
    }
    else
    {
        self.bgImageView.image = [UIImage imageNamed:@"bg_leftMenu3inch@2x.png"];
    }
    self.editMode = kEditNone;
    
    [self reloadState];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [editButton release];
    [localMenuArray release];
    [bgImageView release];
    [currentIndexPath release];
    [sectionDict release];
    [menuArray release];
    [refreshView release];
    [super dealloc];
}

#pragma mark - UITableViewDataSource methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NYMenu *nym = [[MenuDataManager sharedManager].editMenu objectAtIndex:section];
    return nym.children.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [MenuDataManager sharedManager].editMenu.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentify = @"cellIdentify";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if(nil == cell)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify] autorelease];
        
        //添加菜单label
        UILabel *menuLabel = [[UILabel alloc] initWithFrame:CGRectMake(50.f, 0, tableView.frame.size.width-50.f, kMenuSectionViewHeight)];
        menuLabel.font = [UIFont systemFontOfSize:14.f];
        menuLabel.textColor = [UIColor whiteColor];
        menuLabel.highlightedTextColor = [UIColor whiteColor];
        menuLabel.tag = 100;
        menuLabel.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:menuLabel];
        [menuLabel release];
        //添加选中状态
        UIView *bgSelectedView = [[UIView alloc] initWithFrame:cell.bounds];
        bgSelectedView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_section@2x.png"]];
        cell.selectedBackgroundView = bgSelectedView;
        [bgSelectedView release];
    }    
    UILabel *menuLabel = (UILabel *)[cell.contentView viewWithTag:100];
    
    NYMenu *menuFirst = [[MenuDataManager sharedManager].editMenu objectAtIndex:indexPath.section];
    NYMenu *menuSecond = [menuFirst.children objectAtIndex:indexPath.row];
    menuLabel.text = menuSecond.funcName;
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    if(sourceIndexPath.row != destinationIndexPath.row)
    {
        NYMenu *menuFirst = [[MenuDataManager sharedManager].editMenu objectAtIndex:sourceIndexPath.section];
        NYMenu *sourceMenu = [[menuFirst.children objectAtIndex:sourceIndexPath.row] retain];
    
        //移动菜单
        [menuFirst.children removeObject:sourceMenu];
        [menuFirst.children insertObject:sourceMenu atIndex:destinationIndexPath.row];
        [sourceMenu release];
    }
}

#pragma mark - RYPullDownRefreshTableViewDelegate methods
- (void)didTriggerPullDownRefresh
{
    NSString *accountId = nil;
    if([NYMemberCenterDataManager sharedManager].loginMember.accountId &&
       ![[NYMemberCenterDataManager sharedManager].loginMember.accountId isEqualToString:@""])
        accountId = [NYMemberCenterDataManager sharedManager].loginMember.accountId;
    else
        accountId = @"";
    [[MenuDataManager sharedManager] callServerToGetMenuList:accountId];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
//    for(UIView* view in cell.subviews)
//    {
//        if([[[view class] description] isEqualToString:@"UITableViewCellReorderControl"])
//        {
//            for (UIView * subview in view.subviews) {
//                if ([subview isKindOfClass: [UIImageView class]]) {
//                    UIImageView *reorderControl = (UIImageView *)subview;
//                    reorderControl.image = [UIImage imageNamed:@"icon_move.png"];
//                    CGRect rect = reorderControl.frame;
//                    rect.size.width = 10.f;
//                    rect.size.height = 10.f;
//                    reorderControl.frame = rect;
//                }
//            }
//        }
//    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.currentIndexPath = indexPath;
    [self resetSectionsState];
    
    NYMenu *menu = [[MenuDataManager sharedManager].editMenu objectAtIndex:indexPath.section];
    NSDictionary *localMapDict = nil;
    for(NSDictionary *dict in self.localMenuArray)
    {
        if([[dict objectForKey:@"menuName"] isEqualToString:menu.funcName])
        {
            localMapDict = dict;
            break;
        }
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:kHideMenuNotification object:nil];
    BOOL needLogin = [[localMapDict objectForKey:@"menuNeedLogin"] boolValue];
    if(needLogin && ![[NYMemberCenterDataManager sharedManager] isLogin])
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:kShowLoginViewNotification object:nil];
        return;
    }

    NYMenu *firstMenu = [[MenuDataManager sharedManager].editMenu objectAtIndex:indexPath.section];
    NYMenu *secondMenu = [firstMenu.children objectAtIndex:indexPath.row];
    
    NSString *productTypeId = secondMenu.funcId;
    NSString *menuName = secondMenu.funcName;
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:productTypeId forKey:@"productName"];
    [dict setObject:menuName forKey:@"menuName"];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:[localMapDict objectForKey:@"menuNotification"] object:nil userInfo:dict];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kMenuSectionViewHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return kMenuSectionViewHeight;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NYMenu *nym = [[MenuDataManager sharedManager].editMenu objectAtIndex:section];
    NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"MenuSectionView" owner:self options:nil];
    MenuSectionView *msv = (MenuSectionView *)[nibs lastObject];
    
    [self.sectionDict setObject:msv forKey:[NSString stringWithFormat:@"%d",section]];
    msv.menuLabel.text = nym.funcName;
    msv.delegate = self;
    
    NSDictionary *localMapDict = nil;
    for(NSDictionary *dict in self.localMenuArray)
    {
        if([[dict objectForKey:@"menuName"] isEqualToString:nym.funcName])
        {
            localMapDict = dict;
            break;
        }
    }
    
    msv.menuImageView.image = [UIImage imageNamed:[localMapDict objectForKey:@"menuIconNormal"]];
    msv.menuImageView.highlightedImage = [UIImage imageNamed:[localMapDict objectForKey:@"menuIconHighlighted"]];
    
    return msv;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleNone;
}

- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath
{
    if(sourceIndexPath.section == proposedDestinationIndexPath.section)
        return proposedDestinationIndexPath;
    else
        return sourceIndexPath;
}

#pragma mark - action

- (IBAction)settingButtonClicked:(id)sender
{
    [self resetCellState];
    [self resetSectionsState];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kShowSettingViewNotification object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:kHideMenuNotification object:nil];
}

- (IBAction)editButtonClicked:(id)sender
{
    if(self.editMode == kEditingMenu)
    {
        self.editMode = kConfrimingMenu;
    }
    else if(self.editMode == kConfrimingMenu)
    {
        self.editMode = kEditingMenu;
    }
}

#pragma mark - private methord
- (UIViewController*)viewController {
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}

#pragma mark - MenuSectionViewDelegate methods
- (void)didSelectedWithSection:(MenuSectionView *)sectionView
{
    NSInteger index = 0;
    for(NSString *key in [self.sectionDict allKeys])
    {
        MenuSectionView *msv = [self.sectionDict objectForKey:key];
        if(msv == sectionView)
        {
            break;
        }
        index++;
    }
    
    NYMenu *menu = [[MenuDataManager sharedManager].editMenu objectAtIndex:index];
    NSDictionary *localMapDict = nil;
    for(NSDictionary *dict in self.localMenuArray)
    {
        if([[dict objectForKey:@"menuName"] isEqualToString:menu.funcName])
        {
            localMapDict = dict;
            break;
        }
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:kHideMenuNotification object:nil];
    BOOL needLogin = [[localMapDict objectForKey:@"menuNeedLogin"] boolValue];
    //当前菜单需要手势密码同时用户未解过手势密码同时用户手势密码是打开状态
    NSDictionary *userDict = [[NSUserDefaults standardUserDefaults] dictionaryForKey:kIsGestureAuthed];
    NSString *isopen = [userDict objectForKey:[NYMemberCenterDataManager sharedManager].loginMember.accountId];
    
    if(needLogin && ![isopen isEqualToString:@"1"] &&
       [[NYMemberCenterDataManager sharedManager].loginMember gestureOpen])
    {
        lockPage = kAccountProductPage;
        //需要手势密码打开的菜单
        [self refreshPersonalInfoResponseWithNotification:nil];
        return;
    }
    [self resetSectionsState];
    [self resetCellState];
    [sectionView setSectionHighlighted:YES];
    
    NSString *productTypeId = menu.funcId;
    NSString *menuName = menu.funcName;
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:productTypeId forKey:@"productName"];
    [dict setObject:menuName forKey:@"menuName"];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:[localMapDict objectForKey:@"menuNotification"] object:nil userInfo:dict];
}
@end
